package com.aboo.infrastructure.mybatis;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/*
 * @description
 * @author Yata.Niko
 * @version 1.0
 * @date 2024/3/30
 */
public class MyBatisCRUDExample {
    private SqlSessionFactory sqlSessionFactory;

    @BeforeEach
    public void setup() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }

    @AfterEach
    public void teardown() {
        sqlSessionFactory = null;
    }

    @Test
    public void testCRUDOperations() {
        try (SqlSession session = sqlSessionFactory.openSession()) {
            UserMapper userMapper = session.getMapper(UserMapper.class);

            // Create
            User newUser = new User();
            newUser.setUserCode("011");
            newUser.setUserName("大象");
            newUser.setAge(20);
            userMapper.createUser(newUser);
            session.commit();

            // Read
            List<User> allUsers = userMapper.getAllUsers();
            for (User user : allUsers) {
                System.out.println(user);
            }

            // Update
            User existingUser = allUsers.get(5);
            existingUser.setUserCode("012");
            existingUser.setUserName("狮子");
            existingUser.setAge(18);
            userMapper.updateUser(existingUser);
            session.commit();

            // Delete
            userMapper.deleteUser(existingUser.getId());
            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
